package Algorithms.ViolenceMatch_04;

/*
 * @Author 罗
 * @date 2020/3/29 - 7:47 下午
 *
 */

public class ViolenceMatches {
    /**
     * 暴力匹配算法2.0
     * @param origin
     * @param key
     * @return
     */
    public static int violenceMatch2(String origin, String key) {
        char[] c1 = origin.toCharArray();
        char[] c2 = key.toCharArray();
        int i = 0;
        int j = 0;
        while (i < c1.length && j < c2.length) {
            if (c1[i] == c2[j]) {
                i++;
                j++;
            } else {
                i = i - j + 1;
                j = 0;
            }
        }
        if (j == c2.length) {
            return i - j;
        }

        return -1;
    }
    /**
     * 暴力匹配算法
     *
     * @param origin
     * @param key
     * @return
     */
    @Deprecated
    public static int violenceMatch(String origin, String key) {
        int start = 0;
        int targetCounter = 1;
        String temp;
        String compare;
        while (start + targetCounter < origin.length()) {
            temp = origin.substring(start, start + targetCounter);
            compare = key.substring(0, targetCounter);
            if (temp.contentEquals(compare)) {
                if (targetCounter == key.length()) {
                    return start;
                }
                targetCounter++;

            } else {
                //start = start + targetCounter - targetCounter + 1;
                start++;
                targetCounter = 1;
            }

        }

        return -1;
    }


}
